package me.youline.dataServer.service.support.file;

import javax.annotation.PostConstruct;

import me.youline.dataServer.ConfigConstants;

import org.perf4j.aop.Profiled;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.util.UriComponentsBuilder;

public abstract class DefaultFileLocator implements FileLocator{
	
	/**
	 * web资源根路径
	 */
	@Value("#{frontProperties['resource.webRoot']}")
	private String webResourceRoot;
	
	/**
	 * 文件系统资源存放根路径
	 */
	@Value("#{frontProperties['resource.fileRoot']}")
	private String globalFileResourceRoot;
	
	/**
	 * 当前该类型的文件资源存放根目录
	 */
	private String fileRoot;
	
	/**
	 * web资源访问主域名
	 */
	private String webHost;
	
	/**
	 * web资源访问端口
	 */
	private Integer webPort;
	
	@PostConstruct
	protected void init(){
		fileRoot = globalFileResourceRoot + ConfigConstants.PATH_SEPARATOR + this.getFileCategoryName(); 
		if(webResourceRoot.contains(":")){
			String[] splitArray = webResourceRoot.split(":");
			webHost = splitArray[0];
			webPort = Integer.parseInt(splitArray[1]);
		}else{
			webHost = webResourceRoot;
		}
	}
	
	@Override
	public String getFileWebUrl(String url){
		return getHttpUrlStr(combineUrlSegment(getFileCategoryName(),url));
	}
	
	@Override
	public String getFileRoot(){
		return fileRoot;
	}
	
	
	public String getWebResourceRoot() {
		return webResourceRoot;
	}
	
	public String getGlobalFileRoot(){
		return this.globalFileResourceRoot;
	}
	
	/**
	 * 根据指定路径创建http请求地址
	 * @param path
	 * @return
	 */
	@Profiled(tag = "service-获取http路径")
	protected String getHttpUrlStr(String path){
		UriComponentsBuilder builder =  UriComponentsBuilder.newInstance().scheme("http").host(webHost);
		if(webPort != null){
			builder.port(webPort);
		}
		return builder.path(path).toUriString();
	}
	
	protected String combineUrlSegment(String previousSeg,String lastSeg){
		if(previousSeg.endsWith(ConfigConstants.PATH_SEPARATOR) || lastSeg.endsWith(ConfigConstants.PATH_SEPARATOR)){
			return previousSeg+lastSeg;
		}else{
			return previousSeg+ConfigConstants.PATH_SEPARATOR+lastSeg;
		}
	}

	/**
	 * 获取文件类型名称
	 * @return
	 */
	abstract protected String getFileCategoryName();
	
}
